package com.mcc.collect.opc.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.mcc.collect.cache.domain.PlcCache;
import com.mcc.collect.cache.service.IPlcCacheService;
import com.mcc.collect.config.GlobalVar;
import com.mcc.collect.opc.service.IHandleService;
import com.mcc.collect.opc.utils.TimingUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class HandleServiceImpl implements IHandleService {

    @Autowired
    private IPlcCacheService plcCacheService;

    @Qualifier("jmsTemplate")
    @Autowired
    private JmsTemplate jms;

    private final String[] pushCodes = {
            "cp3_hmd3"
    };

    @Override
    public void pushMq(String code, Object nodeValue, Date dt, Integer cacheType, Object preValue) {
        if (!StrUtil.equalsAny(code, pushCodes)) {
            return;
        }

        JSONObject json = new JSONObject();
        json.set("code", code);
        json.set("nodeValue", nodeValue);
        json.set("dt", dt);
        json.set("cacheType", cacheType);
        json.set("preValue", preValue);

        jms.convertAndSend(new ActiveMQQueue("DATA.TRACK"), json.toString());
    }

    @Override
    public void saveNode(String code, Object nodeValue, Date dt, PlcCache plcCache, Object preValue) {
//        log.info(code + "," + nodeValue + "，" + DateUtil.formatDateTime(dt));
        //开关信号变化存储
        if (plcCache.getCacheType() == 2) {
            plcCacheService.setCacheValue(code, nodeValue, dt);
            Integer cacheIsSave = Convert.toInt(plcCache.getCacheIsSave(), 0);
            if (cacheIsSave == 1 && Convert.toInt(nodeValue, 0) != Convert.toInt(preValue, 0)) {
                plcCacheService.insertHisStatus(code, nodeValue, dt);
            }
        }
        TimingUtil.record(dt.getTime(), "开关存储", 1000);
    }

    @Override
    public void oneUpdateTrigger(String code, Object nodeValue, Date dt, Integer cacheType, Object preValue) {
        if (!GlobalVar.initOpc) return;
        log.info(code + "," + nodeValue + "，" + DateUtil.formatDateTime(dt));
        //跟踪逻辑
    }
}
